package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tan.model.domain.Admin;
import com.tan.model.vo.AdminVo;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public Map login(Map map) {
        //1.获取请求参数
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String verificationCode = (String) map.get("verificationCode");
        String uuid = (String) map.get("uuid");
        //2.检验验证码
        String redisCode = redisTemplate.opsForValue().get(Constants.CAP_CODE + uuid);
        if (redisCode == null || !redisCode.equals(verificationCode)) {
            throw new BusinessException("验证码错误");
        }
        redisTemplate.delete(Constants.CAP_CODE + uuid);
        //3.根据用户名查询管理对象的admin
       QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
       queryWrapper.eq("username",username);
       Admin admin = adminMapper.selectOne(queryWrapper);
        //4.判断admin对象是否存在，密码是否一致
       password = SecureUtil.md5(password);
        if (admin == null || !admin.getPassword().equals(password)) {
            throw new BusinessException("用户名或密码错误");
        }
        //5.生成token，将token存入redis中，返回token
        Map tokenmap = new HashMap();
        tokenmap.put("id",admin.getId());
        tokenmap.put("username",admin.getUsername());
       String token = JwtUtils.ValidToken(tokenmap);
        //6.返回token
        Map<String,Object> result = new HashMap<>();
        result.put("token",token);
        return result ;
    }

    public AdminVo profile() {
        Long id= AdminHolder.getUserId();
        Admin admin = adminMapper.selectById(id);
        return AdminVo.init(admin);
    }
}
